package com.zzw.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzw.bean.Msg;
import com.zzw.bean.Wallet;
import com.zzw.service.WalletService;
import com.zzw.utils.ExcelUtil;
import com.zzw.utils.RedisUtil;
import com.zzw.utils.WebUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 赵志伟
 * @version 1.0
 */
@SuppressWarnings({"all"})
@Controller
@RequestMapping("myWallet")
public class WalletController {

    @Resource
    private WalletService walletService;
    @Resource
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("listEasyui")
    public String listEasyui() {
        return "mywallet/listEasyui";
    }

    @RequestMapping("listElementUIOne")
    public String listElementUIOne() {
        return "mywallet/listElementUIOne";
    }

    @RequestMapping("listElementUITwo")
    public String listElementUITwo() {
        return "mywallet/listElementUITwo";
    }

    @RequestMapping("getData")
    @ResponseBody
    public Msg selectTchargeBoxList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                    @RequestParam(value = "sort", defaultValue = "") String sort,
                                    @RequestParam(value = "order", defaultValue = "") String order,
                                    @RequestParam(value = "startDate", required = false) String startDate,
                                    @RequestParam(value = "endDate", required = false) String endDate,
                                    Wallet wallet) {
        // 处理日期范围过滤
        if (startDate != null && !startDate.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date start = sdf.parse(startDate);
                wallet.setStartDate(start);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (endDate != null && !endDate.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date end = sdf.parse(endDate);
                // 将结束日期设置为当天的23:59:59
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(end);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                wallet.setEndDate(calendar.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        PageHelper.startPage(pageNum, pageSize, WebUtils.getOrderBy(sort, order));

        List<Wallet> wallets = walletService.listByCondition(wallet);
        PageInfo pageInfo = new PageInfo(wallets, pageSize);

        //页脚数据
        //确保页脚数据是根据查询条件动态生成的，避免统计与分页数据不一致。
        List<Wallet> footer = walletService.getFooterData(wallet);

        return Msg.success()
                .add("pageInfo", pageInfo) //分页数据
                .add("footer", footer);    //页脚数据
    }

    @RequestMapping("save")
    @ResponseBody
    public Msg save(@RequestBody Wallet wallet) {
        return Msg.success(walletService.save(wallet));
    }

    @RequestMapping("update")
    @ResponseBody
    public Msg update(Wallet wallet) {
        return Msg.success(walletService.update(wallet));
    }

    @RequestMapping("delete")
    @ResponseBody
    public Msg delete(Integer id) {
        return Msg.success(walletService.delete(id));
    }

    /**
     * 批量删除钱包数据
     *
     * @param ids 用逗号分隔的ID列表
     * @return 删除结果消息
     */
    @RequestMapping("batchDelete")
    @ResponseBody
    public Msg batchDelete(@RequestParam("ids") String ids) {
        if (ids == null || ids.trim().isEmpty()) {
            return Msg.fail("未选择要删除的记录");
        }

        String[] idArray = ids.split(",");
        int count = walletService.batchDelete(idArray);

        return Msg.success("批量删除成功")
                .add("data", count);
    }

    /**
     * 获取统计数据
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @param wallet    筛选条件
     * @return 统计数据结果
     */
    @RequestMapping("getStatistics")
    @ResponseBody
    public Msg getStatistics(@RequestParam(value = "startDate", required = false) String startDate,
                             @RequestParam(value = "endDate", required = false) String endDate,
                             Wallet wallet) {
        // 处理日期范围
        if (startDate != null && !startDate.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date start = sdf.parse(startDate);
                wallet.setStartDate(start);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (endDate != null && !endDate.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date end = sdf.parse(endDate);
                // 将结束日期设置为当天的23:59:59
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(end);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                wallet.setEndDate(calendar.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        // 获取支出分类统计数据
        List<Map<String, Object>> categoryData = walletService.getCategoryStatistics(wallet);

        // 获取月度收支统计数据
        Map<String, Object> monthlyData = walletService.getMonthlyStatistics(wallet);

        Map<String, Object> result = new HashMap<>();
        result.put("categoryData", categoryData);
        result.put("monthlyData", monthlyData);

        return Msg.success().add("data", result);
    }

    /**
     * 导出钱包数据到Excel
     *
     * @param wallet    查询条件
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @param response  HTTP响应对象
     */
    @RequestMapping("exportExcel")
    public void exportExcel(Wallet wallet,
                            @RequestParam(value = "startDate", required = false) String startDate,
                            @RequestParam(value = "endDate", required = false) String endDate,
                            HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 处理日期范围
        if (startDate != null && !startDate.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date start = sdf.parse(startDate);
                wallet.setStartDate(start);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (endDate != null && !endDate.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date end = sdf.parse(endDate);
                // 将结束日期设置为当天的23:59:59
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(end);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                wallet.setEndDate(calendar.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        // 设置响应头信息
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");

        // 设置文件名
        String fileName = "钱包数据";
        if (request.getHeader("User-Agent").contains("Firefox")) {
            // 火狐 Base64编码
            response.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" +
                    new BASE64Encoder().encode(fileName.getBytes("UTF-8")) + "?=");
        } else {
            // 其他(主流ie/chrome)使用URL编码操作
            response.setHeader("Content-Disposition", "attachment; filename=" +
                    URLEncoder.encode(fileName, "UTF-8"));
        }

        // 查询数据
        List<Wallet> walletList = walletService.listByCondition(wallet);

        // 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream(), Wallet.class)
                // 自动调整列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .sheet("钱包数据")
                .doWrite(walletList);
    }

    /**
     * 导入Excel数据
     *
     * @param excelFile 上传的Excel文件
     * @return 导入结果
     */
    @RequestMapping("importExcel")
    @ResponseBody
    public Msg importExcel(@RequestParam("excelFile") MultipartFile excelFile) {
        if (excelFile == null || excelFile.isEmpty()) {
            return Msg.fail("请选择要导入的Excel文件");
        }

        try {
            // 读取Excel文件
            List<Wallet> walletList = new ArrayList<>();

            try {
                // 使用EasyExcel读取数据
                EasyExcel.read(excelFile.getInputStream(), Wallet.class, new PageReadListener<Wallet>(dataList -> {
                    walletList.addAll(dataList);
                })).sheet().doRead();
            } catch (ExcelAnalysisException e) {
                return Msg.fail("Excel解析失败，请确保文件格式正确");
            }

            if (walletList.isEmpty()) {
                return Msg.fail("Excel文件中没有数据");
            }

            // 批量保存数据
            int count = walletService.batchSave(walletList);

            return Msg.success("成功导入 " + count + " 条数据")
                    .add("count", count);

        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail("导入失败：" + e.getMessage());
        }
    }

    @PostMapping("exportQrCode")
    @ResponseBody
    public Msg exportQrCode(@RequestParam("excelFile") MultipartFile excelFile) {
        if (excelFile == null || excelFile.isEmpty()) {
            return Msg.fail("请选择要导入的Excel文件");
        }
        walletService.exportQrCode(excelFile);
        return Msg.success("任务已提交, 正在生成二维码压缩包");
    }

    /**
     * 下载Excel导入模板
     *
     * @param response HTTP响应对象
     */
    @RequestMapping("downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 设置响应头信息
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");

        // 设置文件名，使用URL编码处理中文
        String fileName = "钱包数据导入模板.xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);

        // 创建模板数据
        List<Wallet> templateData = new ArrayList<>();

        // 示例数据
        Wallet example1 = new Wallet();
        example1.setItem("餐饮消费");
        example1.setAmount(new java.math.BigDecimal("100.00"));
        example1.setType((byte) 1); // 支出
        example1.setCategory("1"); // 餐饮
        example1.setPaymentMethod("1"); // 微信
        templateData.add(example1);

        Wallet example2 = new Wallet();
        example2.setItem("工资收入");
        example2.setAmount(new java.math.BigDecimal("5000.00"));
        example2.setType((byte) 2); // 收入
        example2.setCategory("4"); // 工资
        example2.setPaymentMethod("4"); // 银行卡
        templateData.add(example2);

        // 导出模板
        EasyExcel.write(response.getOutputStream(), Wallet.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .sheet("导入模板")
                .doWrite(templateData);
    }
}
